using System;
using System.Linq;
using Pay.DTO;
using System.Collections.Generic;
using Pay.Data;
using Pay.Service.Cache;
using Pay.Core;
using Pay.IService;
using Pay.TO;
using System.Linq.Expressions;

namespace Pay.Service {
    public class ManageService : ServiceBase, IManageService, IDisposable {
        private IUnitOfWork _iUnitOfWork;

        public ManageService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }

        public manage_dto Get(long id) {
            if (id == 0)
                return null;
            return context.Manages.Where(c => c.Id == id).FromCacheFirstOrDefault<Manage, manage_dto>("Manage");
        }
        public IEnumerable<manage_dto> Get() {
            return context.Manages.FromCache<Manage, manage_dto>("Manage");
        }

        public manage_dto Login(string mobile, string password) {
            if (string.IsNullOrEmpty(mobile))
                throw new ServerErrorException("手机号码没有填写");
            if (string.IsNullOrEmpty(password))
                throw new ServerErrorException("密码没有填写");
            var model = context.Manages.FirstOrDefault(c => c.Mobile == mobile);
            if (model == null)
                throw new ServerErrorException("用户不存在");
            else if (model != null && model.Password != WebHelper.GetPasswrodWithTwiceEncode(password, model.PasswordSalt))
                throw new ServerErrorException("密码不正确");
            model.LoginTime = DateTime.Now.ToUnix();

            _iUnitOfWork.Commit("Manage");

            var user = Get(model.Id);

            return user;
        }


        /// <summary>
        /// 新增平台管理员
        /// </summary>
        /// <param name="dto"></param>
        public int Add(manage_dto dto) {
            if (context.Manages.Exist(c => c.Mobile == dto.mobile))
                throw new ServerErrorException("用户已经是管理员");

            var tags = new List<string> { "Manage" };
            var dt = DateTime.Now.ToUnix();
            var merchant = context.Merchants.FirstOrDefault(c => c.Mobile == dto.mobile && c.OemId == dto.oem_id);
            if (merchant != null) {
                dto.merchant_id = merchant.Id;
                tags.Add("Merchant" + merchant.Id);
                if (dto.role_id == 5) {
                    merchant.IsSupplier = true;
                    var shop = context.ShopInfo.Find(merchant.Id);
                    if (shop == null) {
                        context.ShopInfo.Add(new ShopInfo { CustomerTel = dto.mobile, CreateTime = dt, Id = merchant.Id, Rate = 0.05M, ShopName = merchant.Name + "节点商城" });
                    }
                }
            }

            Manage model = new Manage();
            dto.ToDtoObject<Manage>(model);
            if (merchant != null) {
                model.PasswordSalt = merchant.PasswordSalt;
                model.Password = merchant.Password;
            } else {
                string salt = Guid.NewGuid().ToString("N").Substring(12);
                model.PasswordSalt = salt;
                model.Password = WebHelper.GetPasswrodWithTwiceEncode("123456", salt);
            }
            model.LoginTime = dt;
            context.Manages.Add(model);
            int result = _iUnitOfWork.Commit(tags.ToArray());
            dto.id = model.Id;
            return result;
        }

        /// <summary>
        /// 更新管理员
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int Update(manage_dto dto) {
            var tags = new List<string> { "Manage" };
            var model = context.Manages.FindById(dto.id);
            dto.ToDtoObject<Manage>(model);
            var dt = DateTime.Now.ToUnix();
            var merchant = context.Merchants.FirstOrDefault(c => c.Mobile == dto.mobile && c.OemId == dto.oem_id);
            if (merchant != null) {
                dto.merchant_id = merchant.Id;
                tags.Add("Merchant" + merchant.Id);
                if (dto.role_id == 5) {
                    merchant.IsSupplier = true;
                    var shop = context.ShopInfo.Find(merchant.Id);
                    if (shop == null) {
                        context.ShopInfo.Add(new ShopInfo { CustomerTel = dto.mobile, CreateTime = dt, Id = merchant.Id, Rate = 0.05M, ShopName = merchant.Name + "节点商城" });
                    }
                }
            }
            int result = _iUnitOfWork.Commit(tags.ToArray());
            return result;
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="user_id"></param>
        /// <param name="password"></param>
        /// <param name="re_password"></param>
        /// <returns></returns>
        public int ChangePwd(long user_id, string old_password, string password, string re_password) {
            if (string.IsNullOrEmpty(password))
                throw new ServerErrorException("密码不能是空的");
            if (string.IsNullOrEmpty(re_password))
                throw new ServerErrorException("确认密码不能是空的");
            if (password != re_password)
                throw new ServerErrorException("密码和确认密码不一致");
            var model = context.Manages.Find(user_id);
            if (model == null)
                throw new ServerErrorException("用户不存在");
            if (model.Password != WebHelper.GetPasswrodWithTwiceEncode(old_password, model.PasswordSalt))
                throw new ServerErrorException("原密码不正确");

            model.Password = WebHelper.GetPasswrodWithTwiceEncode(password, model.PasswordSalt);

            int result = _iUnitOfWork.Commit("Manage");
            return result;
        }

        /// <summary>
        /// 删除管理员
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Delete(long id) {
            var model = context.Manages.FindById(id);
            if (!model.RoleId.HasValue)
                throw new ServerErrorException("超级管理员不可以删除");
            context.Manages.Remove(model);
            int result = _iUnitOfWork.Commit("Manage");
            return result;
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int Reset(manage_dto dto) {
            var model = context.Manages.FindById(dto.id);
            model.Password = WebHelper.GetPasswrodWithTwiceEncode("123456", model.PasswordSalt);
            int result = _iUnitOfWork.Commit("Manage");
            return result;
        }

        /// <summary>
        /// 获取角色
        /// </summary>
        /// <param name="user_id"></param>
        /// <returns></returns>
        public role_dto GetRole(long user_id) {
            if (user_id == 0)
                return null;
            var role = context.Manages.FirstOrDefault(c => c.MerchantId == user_id).ToDtoObject<manage_dto>();
            if (role == null)
                return null;
            return context.Roles.FirstOrDefault(c => c.Id == role.role_id).ToDtoObject<role_dto>();
        }
        /// <summary>
        /// 商户获取
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public manage_dto GetManage(long id) {
            if (id == 0)
                return null;
            return context.Manages.Where(c => c.MerchantId == id).FromCacheFirstOrDefault<Manage, manage_dto>("Manage");
        }
    }
}
